package com.aco.party.common.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aco.party.common.entity.BaseEntity;
import com.aco.party.common.entity.PageEntity;
import com.aco.party.common.entity.RtnVo;

/**
 * <b>Title：</b>BaseController.java<br/>
 * <b>Description：</b> Controller继承类，封装一些公用的调用方法<br/>
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseController {
	/**
	 * 列表分页结果输出
	 * 
	 * @param pageEntity
	 * @return 返回eg:["success":true,"totalCount":10,"data":数据列表]
	 */
	protected Map<String, Object> getPagedMap(PageEntity pageEntity) {
		Map<String, Object> modelMap = new HashMap<String, Object>(3);
		modelMap.put("totalCount", pageEntity.getTotalCount());
		modelMap.put("data", pageEntity.getDatas());
		modelMap.put("success", true);
		return modelMap;
	}

	/**
	 * 返回操作成功Map
	 * 
	 * @param rtnVo
	 * @return eg:返回["success":true,data:数据]
	 */
	protected Map<String, Object> getSucMsg(RtnVo rtnVo) {
		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		modelMap.put("data", rtnVo);
		modelMap.put("success", true);
		return modelMap;
	}

	/**
	 * 返回操作失败Map
	 * 
	 * @param rtnVo
	 * @return eg:返回["success":false,data:数据]
	 */
	protected Map<String, Object> getFailMsg(RtnVo rtnVo) {
		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		modelMap.put("data", rtnVo);
		modelMap.put("success", false);
		return modelMap;
	}

	/**
	 * 返回操作失败并转换为JSON字符串
	 * 
	 * @param rtnVo
	 * @return eg:{"success":true,"data":{"msg":"成功","obj":null}}
	 * @throws IOException
	 */
	protected String getFailMsg2JSONStr(RtnVo rtnVo){
			
		return JSONObject.fromObject(getFailMsg(rtnVo)).toString();
	}

	/**
	 * 返回操作成功并转换为JSON字符串
	 * 
	 * @param rtnVo
	 * @return eg:{"success":false,"data":{"msg":"成功","obj":null}}
	 */
	protected String getSucMsg2JSONStr(RtnVo rtnVo){
		return JSONObject.fromObject(getSucMsg(rtnVo)).toString();
	}

	/**
	 * 判断字符串是否为NULL或空串
	 * 
	 * @param value
	 *            判断字符串
	 * @return true or false
	 */
	protected boolean isEmptyString(String value) {
		return value == null || "".equals(value.trim());
	}

	/**
	 * 判断字符串是否非空（非null和非""）
	 * 
	 * @param value
	 *            判断字符串
	 * @return true or false
	 */
	protected boolean isNotEmptyString(String value) {
		return value != null && !"".equals(value.trim());
	}

	/**
	 * 获得HttpServletRequest
	 * 
	 * @return
	 * @see javax.servlet.http.HttpServletRequest
	 */
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
	}
	
	protected String getCtxPath() {
		return getRequest().getScheme() + "://"
				+ getRequest().getHeader("host")
				+ getRequest().getContextPath();
	}

	/**
	 * 获得HttpSession
	 * 
	 * @return
	 * @see javax.servlet.http.HttpServletRequest
	 */
	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 封装自定义参数动态字段
	 * 
	 * @param baseEntity
	 */
	protected void initDynamicFiles(BaseEntity baseEntity) {
		Map<String, Object> map = (Map) getRequest().getParameterMap();
		if (map != null) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (entry.getKey().contains("dynamicFields.") && entry.getValue() != null) {
					Object[] objArr = (Object[]) entry.getValue();
					if (objArr.length == 1 && objArr[0] != null && objArr[0].toString().trim().length() > 0) {
						baseEntity.setField(entry.getKey().replace("dynamicFields.", ""), objArr[0]);
					}
				}
			}
		}
	}

	/**
	 * 设置分页属性.
	 * 
	 * @param domain
	 *            输入DO对象
	 */
	protected void setPagination(BaseEntity domain) {
		// 封装自定义参数动态字段
		initDynamicFiles(domain);
		int start = Integer.valueOf((String) (getRequest()
				.getParameter("start") != null ? getRequest().getParameter(
				"start") : "1"));
		int limit = Integer.valueOf((String) (getRequest()
				.getParameter("limit") != null ? getRequest().getParameter(
				"limit") : "10"));
		String sort = getRequest().getParameter("sort");
		String order = getRequest().getParameter("order");
		// 设置分页属性: start,limit,sort,order
		domain.setStart(((start - 1) * limit) + 1);
		domain.setEnd(start * limit);
		if (StringUtils.defaultString(sort).toLowerCase().contains("name")) {
			domain.setField("pySort", sort);
			domain.setSort(null);
		}else{
			domain.setSort(sort);
		}
		domain.setOrder(order);
	}
}
